﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.IO.Compression;
using System.IO;
using System.Web;

namespace RealDebridClient
{
    public class Client
    {
        private string realDebridUnrestrictFormat = "http://www.real-debrid.com/lib/ajax/generator.php?login={0}&pass={1}&link={2}&sl=1";

        public Client(){}
        //--------------------------------------------------------------------------------
        public Uri unrestrictLink(Uri link)
        {
            WebClient wc = new WebClient();
            wc.Headers.Add(HttpRequestHeader.AcceptEncoding, "Accept-Encoding: gzip,deflate");
            wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.24) Gecko/20111107 Ubuntu/10.10");
            
            string encodedPass = HttpUtility.UrlEncode(global::RealDebridClient.Properties.Settings.Default.Password);
            byte[] resgzip = wc.DownloadData(string.Format(realDebridUnrestrictFormat, Properties.Settings.Default.Username, encodedPass, link.AbsoluteUri));
            GZipStream gzip = new GZipStream(new MemoryStream(resgzip), CompressionMode.Decompress);
            byte[] resungzip = new byte[2048];
            int count = gzip.Read(resungzip, 0, 2048);
            string reslink = Encoding.ASCII.GetString(resungzip, 0, count);

            if (!Uri.IsWellFormedUriString(reslink, UriKind.Absolute))
                throw new Exception(reslink); // contains error message

            return new Uri(reslink);
        }
        //--------------------------------------------------------------------------------
    }
}
